﻿using System.Collections.Generic;
using ESRI.ArcGIS.Geodatabase;
using Inovout.Gis;
using Inovout.Gis.Geometry;

namespace Inovout.ArcGis
{
    public sealed class ArcGisTable : IGisTable
    {
        private ITable table;
        private IGeometryLayerInfo geometryLayer;
        internal ITable ArcTable
        {
            get { return table; }
        }
        public string Name
        {
            get
            {
                IDataset dataset = table as IDataset;
                string name = dataset.BrowseName;
                if (name.Contains("."))
                {
                    int lastDotIndex = name.LastIndexOf(".");
                    name = name.Substring(lastDotIndex + 1, name.Length - lastDotIndex - 1);
                }
                return name;
            }
        }
        private FeatureLayerInfo layer;
        internal FeatureLayerInfo Layer
        {
            get { return layer; }
            set { layer = value; }
        }
        private List<IGisRow> rows;
        public IEnumerable<IGisRow> Rows
        {
            get
            {
                if (rows == null)
                {
                    rows = new List<IGisRow>();
                    ICursor cursor = table.Search(null, true);
                    IRow row;
                    while ((row = cursor.NextRow()) != null)
                    {
                        ArcGisRow arcGisRow = new ArcGisRow(row);
                        arcGisRow.SetTable(this);
                        rows.Add(arcGisRow);
                    }
                }
                return rows;
            }
        }
        internal ArcGisTable(IFeatureClass featureClass)
            : this(featureClass as ITable)
        {
        }

        public IGisDataSource DataSource
        {
            get { return new ArcDataSource(((IFeature)table).Class); }
        }

        internal ArcGisTable(FeatureLayerInfo geometryLayer)
            : this(geometryLayer.ArcLayer as ITable)
        {
            this.geometryLayer = geometryLayer;
        }

        internal ArcGisTable(ITable table)
        {
            this.table = table;
        }

        public IEnumerable<IGeometryInfo> GetGeometryInfos()
        {
            List<IGeometryInfo> geometries = new List<IGeometryInfo>();
            foreach (IGisRow row in Rows)
            {
                geometries.Add(row.BuildGeometryInfo());
            }
            return geometries;
        }


        public IGisRow GetRow(object geometryId)
        {
            return new ArcGisRow(table.GetRow(int.Parse(geometryId.ToString())));
        }


        public bool HasField(string fieldName)
        {
            return table.FindField(fieldName) > -1;
        }
    }
}
